<?php

use App\Enums\AssetSourceType;
use App\Enums\TokenLockType;
use App\Enums\TokenStatus;
use App\Models\Asset;
use App\Models\ProductToken;

require __DIR__ . '/../vendor/autoload.php';

$app = require_once __DIR__ . '/../bootstrap/app.php';

$app->make(\App\Console\Kernel::class)->bootstrap();

/* ============== Write Codes Below ================= */

echo '>>> Start Laravel from CLI' . PHP_EOL;

$productId = 10627;
$product = \App\Models\Product::query()->find($productId);

// 修复资产对应的product token状态
$assets = Asset::query()->where('contract_address', $product->contract_address)->get();
foreach ($assets as $asset) {
    $token = ProductToken::query()->where('product_id', $productId)->where('token_id', $asset->token_id)->first();

    $token->lock_refer_id = $asset->source_id;
    if ($asset->source_type->is(AssetSourceType::AIRDROP)) {
        $token->lock_type = TokenLockType::AIRDROP();
    } elseif ($asset->source_type->is(AssetSourceType::ORDER())) {
        $token->lock_type = TokenLockType::ORDER();
    }
    $token->status = TokenStatus::SOLD();
    $token->save();
}

// 查找所有转账失败的订单或未转账的订单
$orders = \App\Models\Order::query()->where('product_id', $productId)
    ->where('order_status', \App\Enums\OrderStatus::PAID)
    ->where(function ($q1) {
        return $q1->where('trans_status', \App\Enums\TransStatus::FAILED)
            ->orWhereNull('trans_status');
    })->get();

foreach ($orders as $order) {
    // 查询订单对应的资产
    $asset = Asset::query()->where('source_type', AssetSourceType::ORDER)
        ->where('source_id', $order->id)
        ->first();
    if ($asset) {
        $order->trans_status = 'success';
        $order->trans_fail_reason = '';
        $order->save();
        echo "订单[{$order->order_no}]查到对应资产，将转账状态标记为成功" . PHP_EOL;

        continue;
    }

    // 查询订单锁定的token
    $token = \App\Models\ProductToken::query()->where('product_id', $productId)
        ->where('lock_type', \App\Enums\TokenLockType::ORDER)
        ->where('lock_refer_id', $order->id)
        ->first();
    if (!$token) {
        // 重新转账
        $order->trans_status = null;
        $order->trans_fail_reason = '';
        $order->save();
        \App\Events\OrderPaid::dispatch($order);
        echo "订单[{$order->order_no}]不存在锁定的token, 重新触发OrderPaid事件" . PHP_EOL;
    }
}
